﻿using System;
using System.Reflection;
using Microsoft.VisualStudio.Shell;

namespace PowerGuiVsx.AssemblyLoadPackage
{
    [PackageRegistration(UseManagedResourcesOnly = true)]
    public class AssemblyLoaderPackage : Package
    {
        private string _installPath;

        protected override void Initialize()
        {
            
        }


        public void GetInstallPath()
        {
            _installPath = String.Empty;
            try
            {
                Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer");
                dynamic msi = Activator.CreateInstance(type);
                foreach (var productcode in msi.Products)
                {
                    string productname = msi.ProductInfo(productcode, "InstalledProductName");
                    if (productname.Contains("Quest PowerGUI"))
                    {
                        _installPath = msi.ProductInfo(productcode, "InstallLocation");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public void LoadAssemblies()
        {
            var scriptEditor = Assembly.LoadFrom(System.IO.Path.Combine(_installPath, "ScriptEditor.exe"));

            var assemblies = scriptEditor.GetReferencedAssemblies();
            foreach (var assembly in assemblies)
            {
                try
                {
                    Assembly.LoadFrom(System.IO.Path.Combine(_installPath, assembly.Name + ".dll"));
                }
                catch { }
            }
        }
    }
}
